package com.share.example.sbsjw.algorithm;

import com.google.common.collect.Range;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.Collection;
import java.util.HashSet;

//范围的分片算法类名称，用于BETWEEN
@Slf4j
public class LongBetweenAlgorithm implements RangeShardingAlgorithm<Long> {

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        int colSize = collection.size();

        Range<Long> valueRange = rangeShardingValue.getValueRange();
        String logicTableName = rangeShardingValue.getLogicTableName();
        Long min = valueRange.hasLowerBound() ? valueRange.lowerEndpoint() : null;//查询下限值
        Long max = valueRange.hasUpperBound() ? valueRange.lowerEndpoint() : null;//查询上限值
        if (min == null || max == null) {
            return collection;
        } else {

            Long tmp = min;
            final Collection<String> tableSet = new HashSet();
            while (tmp <= max) {
                String realtable = AllTableConfig.getPhysicsTableName(logicTableName, tmp);
                if (collection.contains(realtable)) {//将当前取值对应的数据库节点存入返回set中
                    tableSet.add(realtable);
                }

                //包含了所以直接跳过
                if (colSize == tableSet.size()) {
                    break;
                }

                tmp += 1;
            }
            return tableSet;
        }
    }

    private static Integer dealTableName(String physicsTableName) {
        String[] s = physicsTableName.split("_");
        return Integer.parseInt(s[s.length - 1]);
    }
}



